<?php
namespace StarCloud\Library;

trait Period
{
    public static function getCurrentPeriod()
    {
        return self::createPeriod(time());
    }

    public static function getCurrentPeriodStartTimestamp()
    {
        if (ENVIRONMENT == 'production') {
            return strtotime(date('Y-m-d'));
        } else {
            return strtotime(date('Y-m-d H:') .  intval(date('i') / 10) * 10 . ':00');
        }
    }

    public static function getNextPeriodStartTimestamp()
    {
        return self::getCurrentPeriodStartTimestamp() + self::getInterval();
    }

    public static function getPreviousPeriod()
    {
        return self::createPeriod(time() - self::getInterval());
    }

    public static function getNextPeriod()
    {
        return self::createPeriod(time() + self::getInterval());
    }

    public static function getRecentPeriods($count = 7)
    {
        $periods = [];
        $currentTimestamp = time();
        $interval = self::getInterval();
        for ($i = 0; $i < $count; $i++) {
            $periods[] = self::createPeriod($currentTimestamp - $i * $interval);
        }

        return $periods;
    }

    public static function getForwardPeriods($timestamp, $count = 7)
    {
        $periods = [];
        $currentTimestamp = $timestamp;
        $interval = self::getInterval();
        for ($i = 0; $i < $count; $i++) {
            $periods[] = self::createPeriod($currentTimestamp + $i * $interval);
        }

        return $periods;
    }

    public static function getInterval()
    {
        return ENVIRONMENT == 'production' ? 86400 : 600;
    }

    public static function createPeriod($timestamp)
    {
        if (ENVIRONMENT == 'production') {
            return date('Ymd', $timestamp);
        } else {
            // 测试环境每10分钟一个周期
            return date('YmdH', $timestamp) . (int) (date('i', $timestamp) / 10);
        }
    }
}
